from tile import *
import pygame
from pygame.locals import *

NUM_TILES_PER_ROW_COLUMN = 5
DISTANCE_FROM_SIDE = 25
PERC_SCREEN_TO_FIND_TILE_SIZE = .5
TILE_PADDING = 2

'''
' Class to manage the board state
'''
class Board(pygame.Surface):
    def __init__(self, letters, width=NUM_TILES_PER_ROW_COLUMN, height=NUM_TILES_PER_ROW_COLUMN):
        self.tiles = []
        self.tiles_on_screen = []
        self.tile_size = int( ( pygame.display.get_surface().get_width() * PERC_SCREEN_TO_FIND_TILE_SIZE ) / NUM_TILES_PER_ROW_COLUMN )
        pygame.Surface.__init__(self, (pygame.display.get_surface().get_width(), pygame.display.get_surface().get_height() ) )
        for x in xrange(NUM_TILES_PER_ROW_COLUMN):
            self.tiles.append([])
            for y in xrange(NUM_TILES_PER_ROW_COLUMN):
                tile = Tile(letters[(NUM_TILES_PER_ROW_COLUMN * x) + y], x, y, self.tile_size)
                self.tiles[x].append(tile)
                #tile.to_string()
        
        
    def get_tile(self, x, y):
        return self.tiles[x][y]
    
    #draws the board game board
    def update(self, screen):
        for x in xrange(NUM_TILES_PER_ROW_COLUMN):
            for y in xrange(NUM_TILES_PER_ROW_COLUMN):
                tile = self.get_tile(x, y)
                pos = ( ( ( x * self.tile_size ) + (x * TILE_PADDING ) ) + DISTANCE_FROM_SIDE, ( y * self.tile_size ) + ( y * TILE_PADDING ) + DISTANCE_FROM_SIDE )
                screen.blit(tile.draw(pos),  pos)
                rect = pygame.Rect((pos), (self.tile_size, self.tile_size))
                self.tiles_on_screen.append(rect)
                
    def click_tile(self, pos):
        result = None
        rect = pygame.Rect((pos), (1, 1))
        index = rect.collidelist(self.tiles_on_screen)
        if(index >= 0):
            x = index / NUM_TILES_PER_ROW_COLUMN
            y = index % NUM_TILES_PER_ROW_COLUMN
            result = self.get_tile(x, y)
        return result
        